#include <unistd.h> 
#include <stdio.h> 
#include <sys/ipc.h> 
#include "shm_segment.h" 
#include <string.h> 
#include <stdlib.h> 
#include <sys/shm.h> 
#include <errno.h> 
#include <signal.h> 
#include <sys/wait.h> 

void signal_handler(int signo) {
    printf("recv signal<%d>\n", signo);
    exit(0);

    return;
}

int main(int argc, char **argv) {
    const char * str = "hello children!\n";

    key_t key = ftok("./", 1010);
    shm_segment shm;
    int ret = shm.init(key, strlen(str) + 1, false);
    if (ret < 0) {
        printf("shm init error\n");
        return -1;
    }

    strcpy(static_cast<char*>(shm.base_addr), str);

    printf("father pid:%d\n", getpid());

/*    if (signal(SIGCHLD, signal_handler) == SIG_ERR) {*/
        //perror("signal error");
        //return -1;
    //}

    pid_t pid = fork();
    if (pid < 0) {
        perror("fork error!");
        return -1;
    }
    else if (pid == 0){
        shm_segment shm2('2');
        int ret = shm2.init(key, 0, true);
        if (ret < 0) {
            printf("shm init error\n");
            exit(-1);
        }
        printf("pid:%d shm:%s", getpid(), static_cast<char *>(shm2.base_addr));
        sleep(15);
        return 0;
    }

//    while(1) sleep(1);
    printf("wait pid %d\n", wait(nullptr));
    sleep(5);

    return 0;
}
